function activate_slot_popup() {
    ajax_prestation_form();
    ajax_fiche_client();
    ajax_repeat_infos();
}

function remove_option(text) {
    if ($('#localitem_event_type option[value="' + text + '"]').length) {
        $('#localitem_event_type option[value="' + text + '"]').remove();
    }
}
function add_option(value, description) {
    if (!$('#localitem_event_type option[value="' + value + '"]').length) {
        $('#localitem_event_type').append($("<option></option>").attr("value", value).text(description));
    }
}
function resetFieldValue(attrName, value) {
    if ($('input[type="text"][name="' + attrName + '"]').length) {
        $('input[type="text"][name="' + attrName + '"]').val("");

    }
    if ($('select[name="' + attrName + '"]').length) {
        $('select[name="' + attrName + '"]').val($('select[name="' + attrName + '"]').find('option:first').val()).trigger('change').trigger("liszt:updated");

    }
    if ($('input[type="radio"][name="' + attrName + '"]').length || $('input[type="checkbox"][name="' + attrName + '"]').length) {
        $('input[name="' + attrName + '"]').attr('checked', false);
    }
}

function setFieldValue(attrName, value) {
    if ($('input[type="text"][name="' + attrName + '"]').length) {
        if (value != undefined && value.length) {
            $('input[type="text"][name="' + attrName + '"]').val(value);
        }
    }
    if ($('select[name="' + attrName + '"]').length) {
        if (value != undefined && value.length) {
            $('select[name="' + attrName + '"]').val(value).trigger('change').trigger("liszt:updated");
        }
    }
    if ($('input[type="radio"][name="' + attrName + '"]').length || $('input[type="checkbox"][name="' + attrName + '"]').length) {
        $('input[name="' + attrName + '"]').attr('checked', false);
        if (value != undefined && value.length) {
            $('input[name="' + attrName + '"][value="' + value + '"]').attr('checked', true);
        }
    }
}

function close_slot() {
    $('#FORMCONTAINER_localitem').hide();
    if ($('.wc-time:not([data-event-id])').length) {
        $('.wc-time:not([data-event-id])').each(function() {
            $(this).parents('.wc-cal-event:first').remove();
        });
    }
    if ($('.tipsy-s').length) {
        $('.tipsy-s').remove();
    }
}

function reinitialize_slot() {
    $('#FORMCONTAINER_localitem .erra-form-common-close_button').css('display', 'inline');
    $('#FORMCONTAINER_localitem').find('.hidden-client-id').val('');
    $('#FORMCONTAINER_localitem').find('.fiche-client').html('');
    click($('#FORMCONTAINER_localitem .erra-form-common-close_button'), function() {
        close_slot();
    });
    if ($('.calendar-select-client').length) {
        _load_autocomplete($('.calendar-select-client'), c_);
    }
    $('#localitem_repeat_enabled_0').attr('checked', false);
    $('.erra-form-jqueryui-submit_button[name="saveActionLocalStorage"]').show();
    if ($('.extra-save-infos').length) {
        $('.extra-save-infos').remove();
    }
    $('#FORMCONTAINER_localitem').show();
}

function addEventForm(calEvent, $eventForm, $container) {
    // COMMON INFORMATIONS
    //////////////////////
    calEvent.slot_day = parseInt(euro_date_to_timestamp($container.find('#localitem_slot_day').val()), 10);
    calEvent.slot_start = parseInt(hour_str_to_timestamp($eventForm.slot_start), 10);
    calEvent.slot_end = parseInt(hour_str_to_timestamp($eventForm.slot_end), 10);
    calEvent.color = calEvent.slot_color = $eventForm.slot_color;
    calEvent.status_rdv = $eventForm.status_rdv;
    calEvent.prestation_id = parseInt($eventForm.prestation_id, 10);
    calEvent.date_commande = parseInt($eventForm.date_commande, 10);
    calEvent.title = $eventForm.title;
    calEvent.from_internet = parseInt($eventForm.from_internet, 10);
    calEvent.extra_field_1 = $eventForm.extra_field_1;
    calEvent.extra_field_2 = $eventForm.extra_field_2;
    calEvent.extra_field_3 = $eventForm.extra_field_3;
    calEvent.extra_field_4 = $eventForm.extra_field_4;
    calEvent.extra_field_5 = $eventForm.extra_field_5;
    calEvent.occurency = 'original';

    // PRESTATIONS INFORMATIONS
    ////////////////////////////
    if (calEvent.event_type == 'presta') {
        calEvent.client_id = $eventForm.client_id;
        calEvent.paypal = $eventForm.paypal;
        var prestationList = window.calendarCache["ComboPrestaInfos"];
        if (prestationList != undefined) {
            var currentPrestation = prestationList[$('#localitem_prestation_id').chosen().val()];
            if (currentPrestation != undefined) {
                calEvent.title = currentPrestation['name'];
                calEvent.color = currentPrestation['color'];
                calEvent.slot_end = calEvent.slot_start + parseInt(currentPrestation['duree'] * 60, 10);
            }
        }
        // Get phone, address, and phone
        calEvent.nom_client = calEvent.prenom_client = "";
        calEvent.nom_client = $('.fiche-client-title').html();
        calEvent.telephone_client = $('.fiche-client-phone').html();
    } else {
        // SLOT INFORMATIONS
        //////////////////////
        calEvent.repeat_enabled = $('#localitem_repeat_enabled_0').attr('checked') ? 'repeat' : '';
        calEvent.repeat_occurency = $eventForm.repeat_occurency;
        calEvent.repeat_occurency_date = $eventForm.repeat_occurency_date;
        calEvent.repeat_period = $eventForm.repeat_period;
        calEvent.repeat_time = $eventForm.repeat_time;
        calEvent.occurency = is_numeric($eventForm.occurency) ? parseInt($eventForm.occurency, 10) : "";
        calEvent.deleted_occurencies = $eventForm.deleted_occurencies;
        calEvent.content = $eventForm.content;
        calEvent.prestation = $eventForm.prestation;
        var repeat_on_specific_days = new Array();
        $container.find('.specific_days:checked').each(function() {
            repeat_on_specific_days.push($(this).val());
        });
        if (repeat_on_specific_days.length) {
            repeat_on_specific_days = implode('§', repeat_on_specific_days);
            calEvent.repeat_on_specific_days = repeat_on_specific_days;
        }
    }
    return calEvent;
}

function enable_slot_submit(calEvent, $container) {
    $('form[action="saveActionLocalStorage"]').off('submit').on('submit', function(e) {
        serializedEvent = $container.find('select, input, textarea[name^="localitem"]').serializeArray();
        // get full calEvent + client data
        eventObject = {};
        $.each(serializedEvent, function(i, $element) {
            if (strstr($element.name, 'localitem')) {
                key = $element.name.replace('localitem[', '')
                key = key.replace(']', '');
                eventObject[key] = $element.value;
            }
        });
        calEvent = addEventForm(calEvent, eventObject, $container);

        if (calEvent.event_type == 'presta' && !$('.hidden-client-id').val()) {
            setError($container.find('.calendar-select-client'), 'Veuillez selectionner un client');
        } else if (calEvent.event_type == 'slot' && !$('#localitem_title').val().length) {
            setError($('.plage-horaire').find('input:first'), 'Veuillez entrer un titre pour cette plage horaire');
        } else {
            removeError($container.find('.calendar-select-client'));
            removeError($('#localitem_title'));
            // Store action and close popup
            addToLocalStore('SAVE_EVENT', calEvent);
            // TODO : put this in dynaclose
            close_slot();
        }
        return false;
    });
}

function init_new_slot(calEvent, $container) {
    calEvent.id = uniqid();
    // SET EVENT TYPE
    //////////////////
    $desc = $container.find('#localitem_slot_start').parents('div:first').find('.erra___field_description');
    if (window.calendarCache['displayType'] == 'std') {
        if (!calEvent.createdFromSingleClick) {
            calEvent.event_type = 'slot';
            $desc.html('Début de la plage horaire');
            remove_option('web');
            remove_option('presta');
            add_option('slot', 'Plage horaire');
        } else {
            calEvent.event_type = 'presta';
            $desc.html('Heure de la prestation');
            remove_option('web');
            remove_option('slot');
            add_option('presta', 'Prestation');
        }
    } else {
        calEvent.event_type = 'web';
        $desc.html("Début de la disponibilité");
        remove_option('slot');
        remove_option('presta');
        add_option('web', 'Ouverture Internet');
    }
    // TODO : reset comment
    resetFieldValue('localitem[extra_field_1]', "");
    resetFieldValue('localitem[extra_field_2]', "");
    resetFieldValue('localitem[extra_field_3]', "");
    resetFieldValue('localitem[extra_field_4]', "");
    resetFieldValue('localitem[extra_field_5]', "");
    $container.find('#localitem_event_type').val(calEvent.event_type).trigger("liszt:updated");
    // SET TITLE AND AGENDA ID
    //////////////////////////
    calEvent.agenda_id = parseInt(window.agendaIdArray[calEvent.userId], 10);
    $('#localitem_title').val(calEvent.title);
    // TIME SETUP
    /////////////
    var slot_start = timestamp_to_hour_str(new Date(calEvent.start).getTime());
    var realStartTime = new Date(calEvent.start).getTime();
    realStartTime = (calEvent.realStart != undefined) ? new Date(calEvent.realStart).getTime() : new Date(calEvent.start).getTime();
    realStartTime = timestamp_to_euro_date_hybrid(realStartTime);
    var slot_end = timestamp_to_hour_str(new Date(calEvent.end).getTime());
    // Set time infs to field
    $container.find('#localitem_slot_start').data('prev', slot_start).val(slot_start);
    $container.find('#localitem_slot_end').data('prev', slot_end).val(slot_end);
    $container.find('#localitem_slot_day').val(realStartTime);
    $container.find('#localitem_slot_color').val('68A1E5').css('background-color', '#68A1E5').css('color', '#68A1E5');

    enable_slot_submit(calEvent, $container);

    if (calEvent.event_type == 'web') {
        $('#localitem_prestation').parents('.rawField:first').show();
        $('#localitem_prestation').parents('.rawField:first').replaceWith('<div class="rawField">' + window.prestationTrees[calEvent.agenda_id] + '</div>');

        load_dynamic_tree();
        var tree = $(".dynatree-container:visible").dynatree("getTree");
        tree.getNodeByKey('root').expand(true);
        // Select all nodes by default
        $(".dynatree-container:visible").dynatree("getRoot").visit(function(node) {
            node.select(true);
        });
    } else {
        $('#localitem_prestation').val('');
        $('#localitem_prestation').parents('.rawField:first').hide();
    }
}

function init_existing_slot(calEvent, $container) {
    // SET EVENT TYPE
    //////////////////
    $desc = $container.find('#localitem_slot_start').parents('div:first').find('.erra___field_description');
    if (calEvent.event_type == 'slot') {
        $desc.html('Heure de la prestation');
        remove_option('presta');
        remove_option('web');
        add_option('slot', 'Plage Horaire');
        $container.find('#localitem_event_type').val(calEvent.event_type).trigger("liszt:updated");
    } else if (calEvent.event_type == 'presta') {
        $desc.html('Début de la plage horaire');
        remove_option('slot');
        remove_option('web');
        add_option('presta', 'Prestation');
        $container.find('#localitem_event_type').val(calEvent.event_type).trigger("liszt:updated");
    } else {
        calEvent.event_type = 'web';
        $desc.html("Début de la disponibilité");
        remove_option('presta');
        remove_option('slot');
        add_option('web', 'Disponibilité Internet');
        $container.find('#localitem_event_type').val(calEvent.event_type).trigger("liszt:updated");
    }
    $container.find('#localitem_event_type').val(calEvent.event_type).trigger("liszt:updated");
    // SET TITLE AND AGENDA ID
    //////////////////////////
    $('#localitem_title').val(calEvent.title);
    // TIME SETUP
    /////////////
    realStartTime = (calEvent.realStart != undefined) ? calEvent.realStart : calEvent.slot_day;
    realStartTime = timestamp_to_euro_date_hybrid(realStartTime);
    var slot_start = timestamp_to_hour_str(calEvent.slot_start);
    var slot_end = timestamp_to_hour_str(calEvent.slot_end);
    // Set time infs to field
    $container.find('#localitem_slot_start').data('prev', slot_start).val(slot_start);
    $container.find('#localitem_slot_end').data('prev', slot_end).val(slot_end);
    $container.find('#localitem_slot_day').val(realStartTime);
    // COMMON SETUP
    ///////////////
    $container.find('#localitem_slot_color').val(calEvent.color).css('background-color', '#' + calEvent.color).css('color', '#' + calEvent.color);
    $container.find('#localitem_status_rdv').val(calEvent.status_rdv).trigger("liszt:updated");
    $container.find('#localitem_prestation_id').val(calEvent.prestation_id).trigger("liszt:updated");
    $container.find('#localitem_date_commande').val(calEvent.date_commande);
    $container.find('#localitem_title').val(calEvent.title);
    $container.find('#localitem_from_internet').val(calEvent.from_internet);
    resetFieldValue('localitem[extra_field_1]', "");
    resetFieldValue('localitem[extra_field_2]', "");
    resetFieldValue('localitem[extra_field_3]', "");
    resetFieldValue('localitem[extra_field_4]', "");
    resetFieldValue('localitem[extra_field_5]', "");
    if (calEvent.extra_field_1 != undefined) {
        setFieldValue('localitem[extra_field_1]', calEvent.extra_field_1);
    }
    if (calEvent.extra_field_2 != undefined) {
        setFieldValue('localitem[extra_field_2]', calEvent.extra_field_2);
    }
    if (calEvent.extra_field_3 != undefined) {
        setFieldValue('localitem[extra_field_3]', calEvent.extra_field_3);
    }
    if (calEvent.extra_field_4 != undefined) {
        setFieldValue('localitem[extra_field_4]', calEvent.extra_field_4);
    }
    if (calEvent.extra_field_5 != undefined) {
        setFieldValue('localitem[extra_field_5]', calEvent.extra_field_5);
    }
    $container.find('#localitem_occurency').val(calEvent.occurency);
    // PRESTATIONS INFORMATIONS
    ////////////////////////////
    if (calEvent.event_type == 'presta') {
        $container.find('#localitem_client_id').val(calEvent.client_id);
        $('.hidden-client-id').val(calEvent.client_id).trigger('change');
        $container.find('#localitem_paypal').val(calEvent.paypal);
    } else {
        // SLOT INFORMATIONS
        //////////////////////
        $container.find('#localitem_date_commande').val(0);
        $container.find('#localitem_from_internet').val(0);
        repeatEnabledAttrChecked = (calEvent.repeat_enabled == 'repeat') ? true : false;
        $('#localitem_repeat_enabled_0').attr('checked', repeatEnabledAttrChecked);
        if (calEvent.repeat_enabled != undefined && calEvent.repeat_enabled == 'repeat') {
            $('#localitem_repeat_enabled_0').attr('checked', true);
            if (calEvent.repeat_occurency == 'always') {
                $('#localitem_repeat_occurency_0').attr('checked', true);
                $('#localitem_repeat_occurency_1').attr('checked', false);
            } else {
                $('#localitem_repeat_occurency_0').attr('checked', false);
                $('#localitem_repeat_occurency_1').attr('checked', true);
            }
            $('#localitem_repeat_time').val(calEvent.repeat_time).trigger('change').trigger("liszt:updated");
            $('#localitem_repeat_period').val(calEvent.repeat_period).trigger('change').trigger("liszt:updated");
            $('#localitem_repeat_occurency_date').val(calEvent.repeat_occurency_date);
            $('#localitem_content').val(calEvent.content);
            $('#localitem_deleted_occurencies').val(calEvent.deleted_occurencies);
            var repeat_on_specific_days = explode('§', calEvent.repeat_on_specific_days);
            if (repeat_on_specific_days != null && repeat_on_specific_days.length) {
                for (i = 0; i < repeat_on_specific_days.length; i++) {
                    $('input[type="checkbox"].specific_days').each(function() {
                        if ($(this).val().toString() == repeat_on_specific_days[i].toString()) {
                            $(this).prop('checked', true);
                        }
                    });
                }
            }
        }

        if (calEvent.event_type == 'web') {
            $('#localitem_prestation').parents('.rawField:first').show();
            $('#localitem_prestation').parents('.rawField:first').replaceWith('<div class="rawField">' + window.prestationTrees[calEvent.agenda_id] + '</div>');
            var selectedPrestas = explode('§', calEvent.prestation);
            load_dynamic_tree();
            var tree = $(".dynatree-container:visible").dynatree("getTree");
            for (i = 0; i < selectedPrestas.length; i++) {
                if (is_numeric(selectedPrestas[i])) {
                    tree.selectKey(parseInt(selectedPrestas[i]));
                }
            }
            tree.getNodeByKey('root').expand(true);
        } else {
            $('#localitem_prestation').val('');
            $('#localitem_prestation').parents('.rawField:first').hide();
        }

    }
    enable_slot_submit(calEvent, $container);
}


function slot_object_init_static(calEvent) {
    if (!$('#FORMCONTAINER_localitem').is(':visible')) {
        reinitialize_slot();
        fillComboPresta(calEvent);
        var $container = $('#EDIT_IN_PLACE_localitem');
        if (calEvent.id == undefined) {
            init_new_slot(calEvent, $container);
        } else {
            init_existing_slot(calEvent, $container);
        }
        // Post UI init
        activate_slot_popup();
        ui_boot_dynamic();
        resize_now();
    }
}

function ajax_prestation_form() {
    if ($('#localitem_event_type').length) {
        if ($('#localitem_event_type').val() == 'slot' || $('#localitem_event_type').val() == 'web') {
            $('.plage-horaire').show();
            $('.fiche-prestation').hide();
        } else {
            $('.fiche-prestation').show();
            $('.plage-horaire').hide();
        }
    }
    $('#localitem_event_type').change(function() {
        if ($(this).val() == 'slot' || $(this).val() == 'web') {
            $('.plage-horaire').show();
            $('.fiche-prestation').hide();
        }
        if ($(this).val() == 'presta') {
            $('.fiche-prestation').show();
            $('.plage-horaire').hide();
        }
    });
}

function ajax_repeat_infos() {
    // Initiallyhide  all options
    click($('#localitem_title'), function($this) {
        if ($this.val() == 'Nouvel évènement') {
            $this.val('');
        }
    });
    $('#localitem_repeat_occurency_date').hide();
    $('#localitem_repeat_occurency_times').hide();
    $('.repeat-infos').hide();

    // Initially show correctly panels 
    if ($('#localitem_repeat_enabled_0').length && $('#localitem_repeat_enabled_0').is(':checked')) {
        $('.repeat-infos').show();
    }
    click($('#localitem_repeat_enabled_0'), function($this) {
        if ($this.is(':checked')) {
            $('.repeat-infos').slideDown();
        } else {
            $('.repeat-infos').slideUp();
        }
    });

    // SHOW DAYS ?
    if ($('#localitem_repeat_period').length) {
        if ($('#localitem_repeat_period').val() == 'jour' ||
                $('#localitem_repeat_period').val() == 'mois' ||
                $('#localitem_repeat_period').val() == 'an') {
            $('#localitem_repeat_on_specific_days_0').parent('div').parent('div').hide();
        }
    }
    $('#localitem_repeat_period').live('change', function() {
        if ($(this).val() == 'semaine') {
            $('#localitem_repeat_on_specific_days_0').parent('div').parent('div').show();
        } else {
            $('#localitem_repeat_on_specific_days_0').parent('div').parent('div').hide();
        }
    });

    // DURING XXX DAYS
    if ($('#localitem_repeat_occurency_0').length && $('#localitem_repeat_occurency_0').is(':checked')) {
        $('#localitem_repeat_occurency_times').show();
        $('#localitem_repeat_occurency_date').hide();
    }
    click($('#localitem_repeat_occurency_0'), function($this) {
        $('#localitem_repeat_occurency_times').show();
        $('#localitem_repeat_occurency_date').hide();
    });

    // UNTTIL XX/XX/20XX
    if ($('#localitem_repeat_occurency_1').length && $('#localitem_repeat_occurency_1').is(':checked')) {
        $('#localitem_repeat_occurency_date').show();
        $('#localitem_repeat_occurency_times').hide();
    }

    click($('#localitem_repeat_occurency_1'), function($this) {
        $('#localitem_repeat_occurency_date').show();
        $('#localitem_repeat_occurency_times').hide();
    });
}

function ajax_fiche_client() {
    click($('#create-client-ajax'), function($this) {
        $('#create-ajax-user input[type="text"]').each(function() {
            $(this).val('');
        });
        alert_jqueryui($('#create-ajax-user'), "Créér client", "Annuler", function() {
            create_ajax_user($('#create-ajax-user .form'));
        });
    });

    // Initializer la fiche client si la valeur existe
    if ($('.hidden-client-id').length) {
        var $hiddenClientId = $('.hidden-client-id');
        if ($hiddenClientId.val().length && $hiddenClientId.val() > 0) {
            $('.fiche-client .loader').show();
            ajax(WEBROOT + "/getdata/fiche_client", {
                client_id: $hiddenClientId.val()
            }, function(data) {
                $('.calendar-select-client').val('');
                $('.fiche-client').addClass('fiche-client-active').html('<div class="loader"></div>' + data);
                $('.fiche-client .loader').hide();
            });
        }
    }

    $('.hidden-client-id').change(function() {
        // Display loader
        // Try local search
        var foundUser = arrayFinder(cli, $(this).val());
        if (is_array(cli) && foundUser != null) {
            // TODO : binary search algorithm
            $('.fiche-client').addClass('fiche-client-active').html('<center><span class="fiche-client-title">' + ucfirst(strtolower(foundUser['label'])) + '</span></center>');

        }
        // Try db search
        if (is_numeric($('.hidden-client-id').val()) && $('.hidden-client-id').val() > 0) {
            $('.fiche-client .loader').show();
            ajax(WEBROOT + "/getdata/fiche_client", {
                client_id: $hiddenClientId.val()
            }, function(data) {
                $('.calendar-select-client').val('');
                $('.fiche-client').addClass('fiche-client-active').html('<div class="loader"></div>' + data);
                $('.fiche-client .loader').hide();
            });
        }
    });
}

